import { _decorator, Component, Node } from 'cc';
import {Global} from "db://assets/scripts/Global";
const { ccclass, property } = _decorator;

@ccclass('Login')
export class Login extends Component {
    onEnable() {
        const wx = window['wx'];
        if (typeof wx !== 'undefined') {
            this.createWxLoginBtn();
        }
    }

    createWxLoginBtn() {
        const wx = window['wx'];

        wx.requirePrivacyAuthorize({
            success: () => {
                const sysInfo = wx.getSystemInfoSync();

                const button = wx.createUserInfoButton({
                    type: 'text',
                    text: '立即进入游戏',
                    style: {
                        left: sysInfo.windowWidth / 2 - 110,
                        top: sysInfo.windowHeight / 2 - 25,
                        width: 220,
                        height: 50,
                        backgroundColor: '#07C160', // 微信绿色
                        color: '#ffffff',
                        textAlign: 'center',
                        fontSize: 18,
                        lineHeight: 50,
                        borderRadius: 25,
                        boxShadow: '0px 4px 12px rgba(0,0,0,0.15)', // 阴影（仅部分机型支持）
                        borderWidth: 0
                    }
                });


                button.onTap((res) => {
                    if (res.userInfo) {
                        console.log('用户授权成功', res.userInfo);

                        // 隐藏当前节点
                        this.node.active = false;

                        // 销毁按钮
                        button.destroy();

                        // 登录游戏，传入用户信息
                        this.loginGame(res.userInfo);
                    } else {
                        console.log('用户拒绝授权', res);
                    }
                });
            },
            fail: (err) => {
                console.warn('隐私协议未同意，无法创建用户按钮', err);
            }
        });
    }

    private async loginGame(userInfo?: any) {
        const wx = window['wx'];

        try {
            const loginCode: string = await new Promise((resolve, reject) => {
                wx.login({
                    success(res) {
                        if (res.code) resolve(res.code);
                        else reject('wx.login 获取 code 失败');
                    },
                    fail(err) {
                        reject(err);
                    }
                });
            });

            const nickname = userInfo?.nickName || '游客';
            const avatar = userInfo?.avatarUrl || '';

            wx.request({
                url: 'https://jknc.sanjiaomao6.fun/api/game/login',
                method: 'POST',
                data: {
                    code: loginCode,
                    nickname,
                    avatar,
                    platform: 1
                },
                success: (res) => {
                    console.log(userInfo ? '登录成功:' : '游客登录成功:', res.data);
                    if (res.data.code === 1) {
                        Global.token = res.data.data.token;
                        Global.userInfo = res.data.data.user_info;
                    }else {
                        console.error('登录失败:', res.data.msg);
                    }
                },
                fail: (err) => {
                    console.error('登录请求失败:', err);
                }
            });
        } catch (e) {
            console.error('登录流程异常:', e);
        }
    }
}
